<?php
	define("THIS_PAGE", "invoices");
	
if (!isset($_REQUEST["invoiceid"])) { print "<strong>Error:</strong> You cannot access this file directly."; exit; }

require_once($_SERVER["DOCUMENT_ROOT"] . "/../sys/libs/init.lib");
require_once($_SERVER["DOCUMENT_ROOT"] . "/../sys/libs/invoice.lib");
include($_SERVER["DOCUMENT_ROOT"] . "/../sys/includes/adminheader.php");

if (isset($_REQUEST["submit"]) && strtolower($_REQUEST["submit"]) == 'save') {

	$invoiceid = $_REQUEST["invoiceid"];
	$duedate = new CBDate($_REQUEST["inv_duedate"], $config["Locale"]["php_date_fmt"]);
	$_REQUEST["inv_duedate"] = $duedate->toDBString("MySQL");
	$date = new CBDate($_REQUEST["inv_date"], $config["Locale"]["php_date_fmt"]);
	$_REQUEST["inv_date"] = $date->toDBString("MySQL");

	$savedata = array(
		"InvoiceNumber" => $db->quote($_REQUEST["inv_invoicenumber"]),
		"Date" 			=> $db->quote($_REQUEST["inv_date"]),
		"DueDate"		=> $db->quote($_REQUEST["inv_duedate"]),
		"ClientID"		=> $db->quote($_REQUEST["inv_client"]),
		"TermsID"		=> $db->quote($_REQUEST["inv_terms"])
	);

	$db->update("invoice", $savedata, "id = {$invoiceid}");

	$updatedata = array();

	foreach ($_REQUEST["item_itemid"] as $key => $val) {
		if ($val != "" && isset($val)) {
			$itemsavedata = array(
				"InvoiceID" 	=> $db->quote($invoiceid),
				"ItemID"		=> $db->quote($_REQUEST["item_itemid"][$key]),
				"Description"	=> $db->quote(($_REQUEST["item_description"][$key] ? $_REQUEST["item_description"][$key] : "NULL")),
				"Quantity"		=> $db->quote(($_REQUEST["item_quantity"][$key] ? $_REQUEST["item_quantity"][$key] : "NULL")),
				"AmountEach"	=> $db->quote(($_REQUEST["item_amounteach"][$key] ? $_REQUEST["item_amounteach"][$key] : "NULL")),
				"TaxAmount"		=> $db->quote(($_REQUEST["item_taxamount"][$key] ? $_REQUEST["item_taxamount"][$key] : "NULL")),
				"id"			=> $db->quote($key)
			);
			$updatedata[] = $itemsavedata;
		}
	}

	for ($i=0; $i<=count($updatedata); $i++) {
		$id = $updatedata[$i]["id"];
			if (strtolower($id) != 'new' && !is_array($updatedata[$i]["ItemID"])) {
			unset($updatedata[$i]["id"]);
			$db->update("item_invoice", $updatedata[$i], "id = {$id}");
		}
	}

	if ($invoiceid) {
		foreach ($_REQUEST["item_itemid"]["New"] AS $key => $val){
			if ($val != '') {
				$itemsavedata = array(
					"InvoiceID" 	=> $invoiceid,
					"ItemID"		=> $_REQUEST["item_itemid"]["New"][$key],
					"Description"	=> ($_REQUEST["item_description"]["New"][$key] ? $_REQUEST["item_description"]["New"][$key] : "NULL"),
					"Quantity"		=> ($_REQUEST["item_quantity"]["New"][$key] ? $_REQUEST["item_quantity"]["New"][$key] : "NULL"),
					"AmountEach"	=> ($_REQUEST["item_amounteach"]["New"][$key] ? $_REQUEST["item_amounteach"]["New"][$key] : "NULL"),
					"TaxAmount"		=> ($_REQUEST["item_taxamount"]["New"][$key] ? $_REQUEST["item_taxamount"]["New"][$key] : "NULL")
				);
				if ($itemsavedata['ItemID'] != '') { 
					if (!$db->insert("item_invoice", $itemsavedata)) $errors[] = "Unable to Save!";
				}
			}
		}
	}
}

// Get select list and javascript contents
$clients = $db->getarray($queries->clientsSQL());
$items = $db->getarray($queries->productsList());

$js[] = "billto = new Object();";
foreach ($clients as $key => $client) {
	$billto = $client->BillTo;
	str_replace("'", "", $billto);
	$js[] = "billto.id{$client->id} = \"{$billto}\"; \n";
}

$js[] = "items = new Object();";
foreach ($items as $key => $item) {
	$js[] = "
		items.id{$item->id} = new Object(); \n
		var desc = '".str_replace("'","", $item->DefaultDescription)."'
		items.id{$item->id}.Description = desc;
		items.id{$item->id}.Amount = '{$item->Amount}'; \n
		items.id{$item->id}.Tax = '{$item->TaxAmount}'; \n
	";
}

$js[] = "
	function onLoadBillTo() {
		var billtofield = document.getElementById('billto');
		var clientList = document.getElementById('inv_client');
		var clientId = clientList.options[clientList.selectedIndex].value;
		var b = billto['id'+clientId];
		billtofield.value = b;
	}
	onLoadBillTo();
	attachEventListener(document.getElementById('inv_client'), 'change', billTo, false);
	function billTo(event) {
		var billtofield = document.getElementById('billto');
		var clientList = document.getElementById('inv_client');
		var clientId = clientList.options[clientList.selectedIndex].value;
		var b = billto['id'+clientId];
		billtofield.value = b;
	}";

$js[] = "
	var cal1xx = new CalendarPopup('testdiv1');
	cal1xx.showNavigationDropdowns();";

$js[] = "
	attachEventListener(document.getElementById('item_itemid[New][0]'), 'change', populateInvoice, false);
	attachEventListener(document.getElementById('item_itemid[New][0]'), 'change', cloneRow, false);
	attachEventListener(document.getElementById('item_quantity[New][0]'), 'change', updateTotal, false);
	attachEventListener(document.getElementById('exportas'), 'mouseover', cancelExportTimeout, false);
	attachEventListener(document.getElementById('exportas'), 'mouseout', hideExportTimeout, false);

	function populateInvoice(event) {
		var selectrow = event.target.id;
		var rowid = selectrow.substr(11);

		var description = document.getElementById('item_description' + rowid);
		var amount = document.getElementById('item_amounteach' + rowid);
		var taxamount = document.getElementById('item_taxamount' + rowid);
		var itemlist = document.getElementById('item_itemid' + rowid)
		var itemid = itemlist.options[itemlist.selectedIndex].value;

		if (itemid) {
			var item = items['id'+itemid];
			description.value = items['id'+itemid].Description;
			amount.value = items['id'+itemid].Amount;
			taxamount.value = items['id'+itemid].Tax;
		} else {
			description.value = '';
			amount.value = '';
			taxamount.values = '';
		}
	}
	
	function updateTotal(event) {
		if (event.target.id.substr(0,13) == 'item_quantity') {
			var rowid = event.target.id.substr(13);
		}

		var amount = document.getElementById('item_amounteach' + rowid);
		var quantity = document.getElementById('item_quantity' + rowid);
		var taxamount = document.getElementById('item_taxamount' + rowid);
		var total = document.getElementById('rowtotal' + rowid);

		var addTotal = Math.round(parseFloat(((amount.value ? parseFloat(amount.value) : 0) + (taxamount.value ? parseFloat(taxamount.value) : taxamount.value)) * parseInt(quantity.value))*100)/100;

		total.value = addTotal;
	}";

$js[] = "
	function init() {
		myPanel = new YAHOO.widget.Panel('myPanel', { width:'320px', visible:false, constraintoviewport:true, fixedcenter:true } );
		myPanel.render();
		YAHOO.util.Event.addListener('addTerms', 'click', myPanel.show, myPanel, true);
	}
	YAHOO.util.Event.addListener(window, 'load', init);
";

$termsarray = $db->getarray("SELECT * FROM paymentterms;");
$terms = array();
foreach ($termsarray as $k => $val) {
	$terms[$val->id] = $val->Terms;
}

$inv = new invoice($db, $_REQUEST["invoiceid"], TRUE);
$invoice = $inv->invoice;
$payments = $inv->payments;

$duedate = new CBDate($invoice->DueDate, $config["System"]["mysql_date_fmt"]);
$date = new CBDate($invoice->Date, $config["System"]["mysql_date_fmt"]);

$smarty->assign("SITE_WWW", SITE_WWW);
$smarty->assign("FORM_ACTION", $_SERVER["PHP_SELF"]);
$smarty->assign("CLIENT_OPTIONS", $clients);
$smarty->assign("SELECTED_CLIENT", $invoice->ClientID);
$smarty->assign("BILL_TO", $invoice->billTo);
$smarty->assign("INVOICE_DATE", $date->toString());
$smarty->assign("INVOICE_DUEDATE", $duedate->toString());
$smarty->assign("INVOICE_NUMBER", $invoice->InvoiceNumber);
$smarty->assign("AVAILABLE_ITEMS", $items);
$smarty->assign("INVOICE_ITEMS", $inv->items);
$smarty->assign("INVOICE_ID", $invoice->InvoiceID);
$smarty->assign("PAYMENT_TERMS", $terms);
$smarty->display("admin_invoices.tpl");

$smarty->assign("JAVASCRIPT", $js);
$smarty->display("admin_footer.tpl");
?>
